{% extends 'base.html' %}

{% block content %}
<div class="container mt-5">
    <h2>答题页面</h2>

    <!-- 倒计时显示 -->
    <div class="alert alert-info" role="alert">
        剩余时间: <span id="timer"></span>
    </div>

    <form id="answerForm" method="POST" action="{{ url_for('submit_paper', paper_id=paper_id) }}">
        {% for question in questions %}
        <div class="card mb-3">
            <div class="card-body">
                <h5 class="card-title">题目ID: {{ question[0] }}</h5>
                <p class="card-text">
                    {{ question[1] }}
                    {% if question[2] == '选择题' and question[3] %}
                        {% for idx, option in enumerate(question[3].split(',')) %}
                        <br>{{ chr(65 + idx) }}. {{ option }}
                        {% endfor %}
                    {% endif %}
                </p>
                {% if question[2] == '选择题' %}
                <div class="form-group">
                    {% for idx in range(4) %}
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="answer_{{ question[0] }}" id="answer_{{ question[0] }}_{{ chr(65 + idx) }}" value="{{ chr(65 + idx) }}" required>
                        <label class="form-check-label" for="answer_{{ question[0] }}_{{ chr(65 + idx) }}">
                            {{ chr(65 + idx) }}
                        </label>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <div class="form-group">
                    <label for="answer_text_{{ question[0] }}">答案</label>
                    <textarea class="form-control" id="answer_text_{{ question[0] }}" name="answer_{{ question[0] }}" rows="3" required></textarea>
                </div>
                {% endif %}
            </div>
        </div>
        {% endfor %}
        <button type="submit" class="btn btn-primary">提交试卷</button>
    </form>
</div>

<script>
    // 设置考试时长（以秒为单位）
    var totalTime = 180; // 例如，30分钟 = 1800秒

    function startTimer(duration, display) {
        var timer = duration, minutes, seconds;
        var interval = setInterval(function () {
            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            display.textContent = minutes + ":" + seconds;

            if (--timer < 0) {
                clearInterval(interval);
                document.getElementById("answerForm").submit(); // 倒计时结束时自动提交表单
            }
        }, 1000);
    }

    window.onload = function () {
        var display = document.querySelector('#timer');
        startTimer(totalTime, display);
    };
</script>
{% endblock %}